﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Data;
using System.Text.RegularExpressions;

namespace Karbel
{
    /// <summary>
    /// Summary description for ConfExpertGrid
    /// </summary>
    public class ConfExpertGrid
    {
        private System.Data.DataTable dataSource;

        public System.Data.DataTable DataSource
        {
            get { return dataSource; }
            set { dataSource = value; }
        }

        public ConfExpertGrid()
        {
            //
            // TODO: Add constructor logic here
            //
        }



        public Dictionary<string,string> ColumnNames
        {
            get
            {
                var names = new Dictionary<string,string>();
                for (int i = 0; i < DataSource.Columns.Count; i++)
                {
                    string colName = DataSource.Columns[i].ColumnName;
                    names.Add(colName,  GetColumnCaption(colName).Replace("&nbsp;", "").Trim());
                }
                return names;
            }
        }


        public ConfExpertGrid(System.Data.DataTable dataSource)
        {
            // TODO: Complete member initialization
            this.DataSource = dataSource;
        }

        bool selectionEnabled = false;

        public bool SelectionEnabled
        {
            get { return selectionEnabled; }
            set { selectionEnabled = value; }
        }

        public string Generate()
        {
            StringBuilder sb = new StringBuilder();
            int columnCount = DataSource.Columns.Count;
           
            int rowCount = DataSource.Rows.Count;
            int productIdIndex = 0;
            int articleIndex = 0;
            string totalColumns = @"<input type=""hidden"" id=""totalColumns"" value=""x""> ";
            List<int> totalColumnIndexes = new List<int>();
            //sb.Append(@" <table ><tr><td style='width:0px'></td> <td> <TABLE  id=""ce"" class=""ce"">");
            sb.Append(@"<TABLE  id=""ce"" class=""ce""><thead>");

            #region ColumnHeader
            sb.Append("<TR>");
            for (int j = 0; j < columnCount; j++)
            {
                DataColumn col = DataSource.Columns[j];
                sb.Append(@"<Th class=""colheader th" + GetColumnCaption(col.ColumnName).Replace("&nbsp;", "").ToLower().Substring(0, 3) + @""">" + GetColumnCaption(col.ColumnName) + "</Td>");
                if (col.ColumnName.ToLower() == "productıd")
                {
                    productIdIndex = j;
                }
                else if (col.ColumnName.ToLower() == "article")
                {
                    articleIndex = j;                    
                }
                else if (col.DataType == typeof(decimal))
                {
                    totalColumnIndexes.Add(j);
                }
            }

            if (SelectionEnabled)
            {
                sb.Append(@"<Th class=""colheader"" width=""50px"" id=""selection"">&nbsp;Selection</Th>");
            }

            string indexes = String.Join(";", Array.ConvertAll<int, string>(totalColumnIndexes.ToArray(), new Converter<int, string>(Convert.ToString)));
            sb.Append(totalColumns.Replace("x", indexes));

            sb.Append("</TR></thead>"); 
            #endregion

            #region Filter
            sb.Append(@"<tbody> <TR>");
            for (int j = 0; j < columnCount; j++)
            {
                DataColumn col = DataSource.Columns[j];
                if (j != productIdIndex)
                {
                    sb.Append(@"<TD class=""filter"">");
                    string filter = "";

                    var filterControl = HttpContext.Current.Request.Form["filter" + j.ToString()];
                    if (filterControl != null)
                        filter = filterControl.ToString(); 

                    sb.Append(@"<INPUT  TYPE=""TEXT"" name=""filter" + j + @""" id=""filter" + j + @""" onkeyup=""filter();"" value=""" + filter  + @""" ></INPUT>");
                }
              
                else
                {
                    sb.Append(@"<TD class=""filterScan"">");     
                     sb.Append(@"<img  src=""images/zoom4.png"" title=""Click images to zoom-in.""  >");
                }
                sb.Append("</TD>");
            }

            if (SelectionEnabled)
            {
                sb.Append(@"<td class=""filterSelect""><INPUT onchange=""filter()""  TYPE=""checkbox"" id=""chkFilter"" /></td>");
            }

            sb.Append("</TR>"); 
            #endregion

            #region Data
            for (int i = 0; i < rowCount; i++)
            {
                sb.Append("<TR>");
                for (int j = 0; j < columnCount; j++)
                {
                    DataColumn col = DataSource.Columns[j];
                    object cellValue = DataSource.Rows[i][j];

                    if (j == productIdIndex)
                    {
                        string onclick = @" onclick=""sbp('" + cellValue + "','" + "product.ProductName" + "/" + "product.Description" + @"');""";
                        sb.Append(@"<TD valing='middle'><img width=""32"" height=""32"" style=""cursor:pointer"" title=""Click to zoom-in."" src=""../images/articles/S_" + cellValue + @".png""" + onclick + "></TD>");
                    }
                    else if (col.DataType == typeof(decimal))
                    {
                        sb.Append(@"<TD class=""n"">" + Utils.FormatAsMeter(cellValue) + "</TD>");                        
                    }
                    else
                    {
                        sb.Append("<TD>" + cellValue + "</TD>");
                    }
                }

                if (SelectionEnabled)
                {
                    sb.Append(@"<td><input title=""" + DataSource.Rows[i][productIdIndex] + @""" type=""checkbox"" onchange=""s(this)"" id=""c" + i.ToString() + @"""> </td>");
                }

                
                sb.Append("</TR>");
            } 
            #endregion

            #region Total
            sb.Append(@"<TR class=""totalRow"">");

       

            for (int j = 0; j < columnCount; j++)
            {
                DataColumn col = DataSource.Columns[j];
                sb.Append(@"<td class=""totalColumn"">");
                if (col.DataType == typeof(decimal))
                {
                    sb.Append(@"<span class=""totals"" /> ");
                }
                else if (j == articleIndex)
                {
                    sb.Append(@"<span id=""count"" /> ");
                }
                sb.Append("</td>");
            }

            if (SelectionEnabled)
            {
                sb.Append(@"<td class=""selectionFooter"">");
                sb.Append(@"<span class=""selectionFooter"" id=""selectionCount"">No rows selected</span>");
                sb.Append(@"<input type=""hidden"" id=""selectedRows"" name=""selectedRows"">");
                sb.Append(@"</td>");
            }
            sb.Append("</TR>"); 
            #endregion

            //sb.Append("</TABLE></td><td style='width:0px'></td></tr></table>");
            sb.Append(" </tbody> </table>");

            sb.Replace("<", "\r\n<");

            return sb.ToString();
        }

        public List<int> SelectedProductId()
        {
            string vals  = HttpContext.Current.Request.Form["selectedRows"];
            List<int> IDs =  vals.Split(new string[1] {":"}, StringSplitOptions.RemoveEmptyEntries).Select(s => int.Parse(s)).ToList();
            return IDs;
          
        }

        

        public static string GetColumnCaption(string caption)
        {

            if (caption.ToLower() == "productıd")
            {
                return "&nbsp;Scan";
            }

            if (caption.Contains("Qty"))
            {
                caption = caption.Replace("Qty", "") + "Quantity";
            }


            string result = string.Empty;
            MatchCollection mc = Regex.Matches(caption, @"(\P{Lu}+)|(\p{Lu}+\P{Lu}*)");
            string[] parts = new string[mc.Count];
            for (int i = 0; i < mc.Count; i++)
            {
                result += mc[i].ToString() + " ";
            }
            
            return "&nbsp;" +  result;
        }

    } 
}